import 'package:cmd_myapp_demo/components/my_app.dart';
import 'package:cmd_myapp_demo/components/my_home_page.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp(child: _CurveDemo()));
}

class _CurveDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MyHomePage(title: const Text("Curve 动画过程"), child: _CurveAnimationPage());
  }
}

class _CurveAnimationPage extends StatefulWidget {
  @override
  _CurveAnimationPageState createState() => _CurveAnimationPageState();
}

class _CurveAnimationPageState extends State<_CurveAnimationPage> with SingleTickerProviderStateMixin {

  late Animation<double> animation;
  late AnimationController controller;
  double animationValue = 0.0;

  @override
  void initState() {
    super.initState();
    // 初始化动画控制器
    controller = AnimationController(
        // 动画时长
        duration: const Duration(milliseconds: 2000),
        vsync: this
    );

    // 初始化动画,控制动画过程
    animation = CurvedAnimation(parent: controller, curve: Curves.bounceIn);

    // 添加状态监听, 实现循环播放
    animation.addStatusListener((status) {
       if (status == AnimationStatus.completed) {
         controller.reverse();
       } else if (status == AnimationStatus.dismissed) {
         controller.forward();
       }
    });

    // 开始动画
    controller.forward();
  }

  @override
  void dispose() {
    // 销毁
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _AnimationElement(animation: animation);
  }
}


// 颜色动画从透明到不透明 宽高不断变大(往复循环)
class _AnimationElement extends AnimatedWidget {
  static final _opacityTween = Tween<double>(begin: 0.1, end: 1.0);
  static final _sizeTween = Tween<double>(begin: 10.0, end: 300.0);

  final Animation<double> animation;

  const _AnimationElement({required this.animation}): super(listenable: animation);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Opacity(
        // Tween 本身不存任何值,但可以通过 evaluate 拿到
        opacity: _opacityTween.evaluate(animation),
        child: Container(
          margin: const EdgeInsets.symmetric(vertical: 10.0),
          width: _sizeTween.evaluate(animation),
          height: _sizeTween.evaluate(animation),
          child: const FlutterLogo()
        ),
      ),
    );
  }
}